<template>
  <div class="orders-page">
    <!-- 搜索表单 -->
    <el-card class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="支付状态">
          <el-select v-model="searchForm.payment_status" placeholder="请选择状态" clearable>
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="支付失败" value="failed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>

        <el-form-item label="搜索关键词">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入订单号、用户昵称或套餐名称"
            clearable
            style="width: 250px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>订单列表</span>
          <div class="header-actions">
            <el-button @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="orderList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column prop="order_number" label="订单号" min-width="180" />

        <el-table-column label="用户信息" min-width="150">
          <template #default="{ row }">
            <div>
              <div>{{ row.user?.nickname || '未设置' }}</div>
              <div class="text-gray-500 text-sm">{{ row.user?.phone_number || '未绑定' }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="套餐信息" min-width="150">
          <template #default="{ row }">
            <div>
              <div>{{ row.package?.title || '未知套餐' }}</div>
              <div class="text-gray-500 text-sm">{{ row.package?.credits_amount || 0 }} 条</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{ row }">
            ¥{{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>

        <el-table-column label="支付状态" width="120">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.payment_status)"
              class="status-tag"
            >
              {{ getStatusText(row.payment_status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                @click="handleViewDetail(row)"
              >
                查看详情
              </el-button>

              <el-dropdown
                v-if="row.payment_status !== 'paid'"
                @command="(command: string) => handleUpdateStatus(row, command)"
              >
                <el-button type="warning" size="small">
                  更新状态
                  <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="pending" :disabled="row.payment_status === 'pending'">
                      待支付
                    </el-dropdown-item>
                    <el-dropdown-item command="paid" :disabled="row.payment_status === 'paid'">
                      已支付
                    </el-dropdown-item>
                    <el-dropdown-item command="failed" :disabled="row.payment_status === 'failed'">
                      支付失败
                    </el-dropdown-item>
                    <el-dropdown-item command="cancelled" :disabled="row.payment_status === 'cancelled'">
                      已取消
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="700px"
    >
      <div v-if="currentOrder" class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单ID">
            {{ currentOrder.id }}
          </el-descriptions-item>
          <el-descriptions-item label="订单号">
            {{ currentOrder.order_number }}
          </el-descriptions-item>
          <el-descriptions-item label="用户昵称">
            {{ currentOrder.user?.nickname || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="用户手机">
            {{ currentOrder.user?.phone_number || '未绑定' }}
          </el-descriptions-item>
          <el-descriptions-item label="套餐名称">
            {{ currentOrder.package?.title || '未知套餐' }}
          </el-descriptions-item>
          <el-descriptions-item label="包含条数">
            {{ currentOrder.package?.credits_amount || 0 }} 条
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">
            ¥{{ currentOrder.amount.toFixed(2) }}
          </el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="getStatusType(currentOrder.payment_status)">
              {{ getStatusText(currentOrder.payment_status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">
            {{ currentOrder.payment_method || '未知' }}
          </el-descriptions-item>
          <el-descriptions-item label="交易ID">
            {{ currentOrder.payment_transaction_id || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDate(currentOrder.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDate(currentOrder.updated_at) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, ArrowDown } from '@element-plus/icons-vue'
import { orderApi, type Order, type OrderListParams } from '@/api/admin'

// 响应式数据
const loading = ref(false)
const orderList = ref<Order[]>([])
const detailDialogVisible = ref(false)
const currentOrder = ref<Order | null>(null)

// 搜索表单
const searchForm = reactive<OrderListParams>({
  payment_status: undefined,
  search: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: 'warning',
    paid: 'success',
    failed: 'danger',
    cancelled: 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待支付',
    paid: '已支付',
    failed: '支付失败',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString()
}

// 获取订单列表
const getOrderList = async () => {
  loading.value = true
  try {
    const params: OrderListParams = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    const response = await orderApi.getList(params)
    orderList.value = response.data
    pagination.total = response.pagination.total
  } catch (error) {
    console.error('获取订单列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getOrderList()
}

// 重置搜索
const handleReset = () => {
  searchForm.payment_status = undefined
  searchForm.search = ''
  pagination.page = 1
  getOrderList()
}

// 刷新
const handleRefresh = () => {
  getOrderList()
}

// 查看详情
const handleViewDetail = async (order: Order) => {
  try {
    const response = await orderApi.getDetail(order.id)
    currentOrder.value = response.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取订单详情失败:', error)
  }
}

// 更新订单状态
const handleUpdateStatus = async (order: Order, status: string) => {
  try {
    const statusText = getStatusText(status)
    await ElMessageBox.confirm(`确定要将订单状态更新为 "${statusText}" 吗？`, '确认更新', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await orderApi.updateStatus(order.id, status as any)
    ElMessage.success('订单状态更新成功')
    getOrderList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('更新订单状态失败:', error)
    }
  }
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  getOrderList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page
  getOrderList()
}

// 初始化
onMounted(() => {
  getOrderList()
})
</script>

<style scoped>
.orders-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.order-detail {
  padding: 20px 0;
}

.status-tag {
  margin-right: 5px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

.text-gray-500 {
  color: #6b7280;
}

.text-sm {
  font-size: 0.875rem;
}

@media (max-width: 768px) {
  .orders-page {
    padding: 15px;
  }

  .el-table {
    font-size: 12px;
  }

  .el-pagination {
    text-align: center;
  }

  .action-buttons {
    gap: 4px;
  }

  .action-buttons .el-button {
    font-size: 11px;
    padding: 4px 8px;
  }
}
</style>
